<?php

namespace app\modules\backend\controllers;

use app\models\Device;
use app\tools\Re;
use Yii;

class DeviceController extends BaseController
{
    public function actionDeviceList(){
      $name = Yii::$app->request->post('name', '');
      $page = Yii::$app->request->post('page', 0);
      $level = Yii::$app->request->post('level', 2);
      $parent_id = Yii::$app->request->post('parent_id', 0);
      $query = Device::find()->where(['level' => $level, 'status' => [0,1]]);
      if (!empty($name)) {
          $query->andWhere(['like', 'name', $name]);
      }
      if (!empty($parent_id)) {
          $query->andWhere(['parent_id' => $parent_id]);
      }
      $device_list = $query->orderBy('created_at desc')->limit(Device::PAGE_SIZE)->offset(Device::PAGE_SIZE*$page)->all();
      $device_data = [];
      if ($device_list) {
        foreach ($device_list as $v) {
          $device_data[] = [
            'id' => $v->id,
            'name' => $v->name,
            'parent_name' => $v->parent->name,
            'parent_id' => $v->parent_id,
            'level' => $v->level,
            'status' => $v->status,
            'created_time' => date('Y-m-d H:i', $v->created_at)
          ];
        }
      }
      return Re::data([
          'data' => $device_data,
          'totalPage' => $query->count(),
          'currentPage' => $page,
          'perPage' => Device::PAGE_SIZE
      ]);
  }

  public function actionEditDevice(){
      $id = Yii::$app->request->post('id', 0);
      $post = Yii::$app->request->post();
      return $this->edit(Device::class, $id, $post);
  }

  public function actionChangeDeviceStatus(){
      $id = Yii::$app->request->post('id', 0);
      $device = Device::findOne($id);
      if (!$device) {
        return Re::data(null, '设备信息读取错误', Re::ERROR);
      }
      $device->status = $device->status ? 0 : 1;
      $device->save();
      return Re::data();
  }
}
